import React, { useState, useEffect, useReducer } from 'react'
import { NavBar, Toast } from 'antd-mobile'
import "./Shop.less"
import { initState, reducer } from "../Login/user";
import { reqCartdelete, reqCartedit, reqCartlist } from '../../http/api'
import no from "../../assets/img/no.png"
import yes from "../../assets/img/yes.png"
export default function Shop() {
    // 1初始化数据
    const [goodsinfo, setgoodsinfo] = useState([])
    // 4从仓库拿数据
    const [state] = useReducer(reducer, initState)

    const [allChecked, setAllChecked] = useState(false);

    //8.5 首先设置一个开关变量isRequest 默认true
    let isRequest = true
    // 2进页面来取数据
    useEffect(() => {
        reqlist()
    }, [])
    // 3请求列表数据
    const reqlist = async () => {
        let res = await reqCartlist({ uid: state.info.uid })
        if (res.data.code === 200) {
            //9.2 补checked
            let arr = res.data.list[1] ? res.data.list[1].content : [];
            arr.forEach((item) => {
                let obj = goodsinfo.find((i) => i.id == item.id);
                item.checked = obj ? obj.checked : false
            })
            setgoodsinfo(arr)

            //8.6 打开开关
            isRequest = true
        }
    }
    // 9.3 点了一个checked
    const changeOne = (index) => {
        goodsinfo[index].checked = !goodsinfo[index].checked;
        // 修改goodsinfo
        setgoodsinfo([...goodsinfo])
        // 修改全选
        setAllChecked(goodsinfo.every((item) => item.checked))
    }

    // 10 全选
    const changeAll = () => {
        let newAll = !allChecked;
        // 修改全选
        setAllChecked(newAll);
        // 修改goodsinfo
        goodsinfo.forEach((item) => {
            item.checked = newAll;
        });
        setgoodsinfo([...goodsinfo])

    }

    // 6.2删除逻辑
    const del = (id) => {
        reqCartdelete({ id }).then(res => {
            console.log(res);
            if (res.data.code === 200) {
                Toast.success(res.data.msg)
                // 6.3重新渲染列表
                reqlist()
            }
        })
    }
    // 7.2自增逻辑
    const add = (id) => {
        let token = JSON.parse(sessionStorage.getItem("info")).token
        reqCartedit({ id, type: 2, token }).then(res => {
            if (res.data.code === 200) {
                // 7.3重新渲染列表
                reqlist()
            }

        })
    }
    // 8.2自减逻辑
    const sub = (id, num) => {
        // 8.4不能低于1
        if (num <= 1) {
            Toast.info("宝贝不能再少了");
            return;
        }
        if (isRequest) {
            let token = JSON.parse(sessionStorage.getItem("info")).token
            reqCartedit({ id, type: 1, token }).then(res => {
                if (res.data.code === 200) {
                    // 8.3重新渲染列表
                    reqlist()
                }

            })
        }

    }

    // 计算总价
    let allPrice = goodsinfo.reduce((val,item)=>item.checked?val+=item.price*item.num:val,0).toFixed(2)

    return (
        <div className="home">
            <NavBar>商城</NavBar>
            {/*5 渲染数据 */}
            {
                goodsinfo.map((item, index) => (
                    <div key={item.id} className="item">
                        {/* 9.1 单选框选中 */}
                        <div className="check" onClick={() => changeOne(index)}>
                            {item.checked ? <img src={yes} alt="" /> : <img src={no} alt="" />}</div>

                        <img src={item.img} alt="" />


                        <div className="right">
                            <span className="name">{item.goodsname}</span>
                            <span className="price">&yen;{item.price}</span>
                            <div className="num">
                                {/* 7.1做自增 */}
                                <span onClick={() => add(item.id)}>+</span>
                                <i> {item.num}</i>
                                {/* 8.1做自减 */}
                                <span onClick={() => sub(item.id, item.num)}>-</span>
                                {/* 6.1 做删除 */}
                                <div className="button" onClick={() => del(item.id, item.num)}>删除</div>
                            </div>
                        </div>
                    </div>
                ))
            }

            {/* 全选 */}
            <div className="checked" onClick={() => changeAll()}>
                
                {allChecked ?  <img src={yes} alt="" /> : <img src={no} alt="" />}
                <span>全选</span>
                <span className="all">合计：{allPrice}</span>
            </div>
        </div>
    )
}

